/**
 * Created by luckyjing on 16/3/24.
 */
var Util = require('../util/util');
var Article = require('mongoose').model('Article');

exports.articleByID = function (req, res, next, id) {
    Article.findOne({
        _id: id
    }, function (err, article) {
        if (err) {
            return next(err);
        } else {
            req.article = article;
            next();
        }
    })
};
exports.update = function (req, res) {
    Article.findByIdAndUpdate(req.article.id, req.body, function (err, article) {
        if (err) {
            res.json(Util.Info.ERROR);
        } else {
            res.json(Util.Info.SUCCESS);
        }
    })
};
exports.create = function (req, res) {
    var article = new Article(req.body);
    article.creator = req.user;
    article.save(function (err) {
        if (err) {
            res.json(Util.Info.ERROR);
        } else {
            res.json(Util.Info.SUCCESS)
        }
    })
};
exports.list = function (req, res) {
    Article.find({creator: req.user}).sort('-created')
        .exec(function (err, articles) {
            if (err) {
                res.json(Util.Info.ERROR);
            } else {
                res.json(articles);
            }
        })
};
exports.read = function (req, res) {
    res.end(req.article);
};